import numpy as np
import matplotlib.pyplot as plt

"""构造数据"""
x = 2 * np.random.rand(100, 1)
y = 4 + 3 * x + np.random.randn(100, 1)

"""画出图像"""
# plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
# plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
# plt.plot(x, y, 'b.')
# plt.xlabel("x")
# plt.ylabel("y")
# plt.axis([0, 2, 0, 15])  # 设置坐标轴取值范围
# plt.show()

"""对数据集添加偏置项"""
x_b = np.c_[np.ones([100, 1]), x]  # 加上一列1，横向用r_
# print(x_b)
"""根据最小二乘法公式得到参数矩阵"""
theta_best = np.linalg.inv(x_b.T.dot(x_b)).dot(x_b.T).dot(y)
print(theta_best)

"""测试参数"""
x_new = np.array([[0], [2]])  # 构造 新数据
x_new_b = np.c_[np.ones([2, 1]), x_new]  # 加一列偏置项
y_predict = x_new_b.dot(theta_best)
print(y_predict)

"""将预测点画在图上"""
plt.plot(x_new, y_predict, 'r--')
plt.plot(x, y, 'b.')
plt.axis([0, 2, 0, 15])  # 设置坐标轴取值范围
plt.show()




